import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import qs from 'query-string'
import api from './../../serve/api'
import Tab from './../../components/common/TabVertical'
import Content from './../../components/common/Content'
import Page from './../../components/common/Page'
import Empty from './../../components/common/Empty'

import './OrgEva.css'

class OrgEva extends Component {

  constructor(props) {
    super(props)
    const { id } = qs.parse(props.location.search)
    this.state = {
      selected: 0,
      types: [],
      datas: [],
      typeId: Number(id) || '',
      pageTotal: '',
      page: 1,
      pageSize: 15
    }
  }

  getCurrentPage(currentPage) {
    this.getEvaluation(this.state.typeId, currentPage)
  }

  componentDidMount() {
    this.getEvaluationTypeAll()
  }

  async getEvaluationTypeAll() {
    const data = await api.listEvaluationTypeApi()
    if (data && data.code === '000000') {
      this.setState({
        types: data.result
      })
      if (data.result.length > 0) {
        const first = data.result[0]
        if (this.state.typeId !== '') {
          let selected = 0
          data.result.some((item, index) => {
            if (item.id === this.state.typeId) {
              selected = index
              return true
            }
          })
          this.setState({
            selected
          })
          this.getEvaluation(this.state.typeId , this.state.page)
        } else {
          this.getEvaluation(first.id, this.state.page)
        }
      }
    }
  }

  async getEvaluation(typeId, page) {
    const data = await api.listEvaluationApi({ typeId, page, pageSize: this.state.pageSize })
    if (data && data.code === '000000') {
      this.setState({
        page,
        typeId,
        datas: data.result || [],
        pageTotal: data.resultNum
      })
    }
  }

  onTab(item, index) {
    this.setState({
      selected: index,
      typeId: item.id
    })
    this.getEvaluation(item.id, 1)
  }

  onItem(item) {
    this.props.history.push(`/mainPage/commonDetail/evaluation/${item.id}`)
  }

  render() {
    const { selected, types, datas, pageTotal, page } = this.state
    return (
      <div className="org_eva">
        <Tab tabs={types} selected={selected} onTab={(item, index) => this.onTab(item, index)} />
        <div className="eva_content">
          {datas.length === 0 && <Empty title="暂无数据" />}
          {datas.length > 0 && <Content datas={datas} onItem={item => this.onItem(item)} />}
          {datas.length > 0 && <Page 
            pageConfig={{totalPage: pageTotal, pageSize: this.state.pageSize, currentPage: page }}
            pageCallbackFn={currentPage => this.getCurrentPage(currentPage)}
          />}
        </div>
      </div>
    )
  }
}

export default withRouter(OrgEva)
